<template>
  <div id="chat">
    <van-sticky class="cust-van-sticky">
      <div class="cust-van-tabs">
        <div style="padding-top: 18px;">
          <van-tabs v-model:active="active" swipeable @change="onTabChange"
             color="#ffffff" title-active-color="#ffffff" background="#3286A0"
             title-inactive-color="#ffffff" shrink line-width="22px">
            <van-tab name="public">
              <template #title> 消息 </template>
            </van-tab>
          </van-tabs>
        </div>
      </div>
    </van-sticky>

    <!-- <van-sticky class="cust-van-sticky">
      <div class="cust-van-tabs">
        <van-tabs v-model:active="active" swipeable shrink @change="onTabChange"
          line-width="0" color="#323233" title-active-color="#323233">
          <van-tab title="消息" name="message" />
        </van-tabs>
      </div>
    </van-sticky> -->
    <div class="usersList">
      <van-cell v-for="item in users" center @click="chatBoxClick(item)">
        <template #title>
          <van-badge dot>
            <van-image class="my-van-image"
              round
              fit="cover"
              width="4rem"
              height="4rem"
              :src="item.avatarUrl"
            />
          </van-badge>
          <div class="userInfo" style="display: inline-block;">
            <div class="userName">{{item.username}}</div>
            <!-- <div class="latest-new">你好,在吗</div> -->
          </div>
        </template>
        <template #value>
          <div class="time">{{ formatDate(item.updateTime) }}</div>
        </template>
      </van-cell>
    </div>

    <!-- <van-cell center @click="chatBoxClick">
      <template #title>
        <van-image class="my-van-image"
          round
          fit="cover"
          width="4rem"
          height="4rem"
          src="https://tse2-mm.cn.bing.net/th/id/OIP-C.XM_QsL3j93XWugrLGvkc_QHaGv?w=197&h=179&c=7&r=0&o=5&dpr=1.1&pid=1.7"
        />
        <div class="userInfo" style="display: inline-block;">
          <div class="userName">等闲22</div>
          <div class="latest-new">你好,在吗</div>
        </div>
      </template>
      <template #value>
        <div class="time">2023-02-24</div>
        <van-badge :content="2" style="margin: 10px 10px 0 0;"/>
      </template>
    </van-cell> -->
  </div>
</template>

<script setup lang="ts">

import {ref, onMounted, computed} from 'vue';
import { useRouter } from 'vue-router';
import { useCache } from '../../hooks/useCache';

import {useAppStoreWithOut} from '../../store/modules/app.ts';
import myAxios from '../../plugins/myAxios.ts';

const users = ref();//聊天列表的信息

onMounted(() => {
  showUsers();

  // getHistoryMessage();
})

const active = ref('message');
const onTabChange = (name: String) => {}
const messages = ref<API.Im[]>([]);
const router = useRouter();
const {wsCache} = useCache();
const appStore = useAppStoreWithOut();
const limitMessage = ref(10);



//获取历史消息

const chatBoxClick = (item) => {
  // window.sessionStorage.setItem('currentSession', JSON.stringify(item));
  wsCache.set(appStore.getCurrentSessionToUser, item);
  router.push({
    path: '/chatPerson'
  })
}

//取出聊天列表的信息
const showUsers = async() => {
  users.value = wsCache.get(appStore.getChatUsersList);

  const res = await myAxios.get('/im/chat/users')
    if(res.code == 40001) {
        users.value = [];
    }

  if(res.code == 0) {
    //如果请求有聊天用户列表
      // console.log("res.data=>",res.data)
      // console.log("users.value",users.value)
    if(res.data) {

      if(users.value == null || users.value.length == 0) {

        users.value = [];
        res.data.forEach(chatUser => {
          users.value.push(chatUser);
        });
      }
      //请求的列表与当前的列表合并，没有重复值===>数组对象去重
      res.data.forEach(chatUser => {

        users.value.push(chatUser);
      });
      // 序列化去重
        // users.value = [...new Set(users.value.map(item => JSON.stringify(item)))];
        users.value = [...new Map(users.value.map(item => [item.id, item])).values()];
        console.log("users=>",JSON.stringify(users.value))
      // 反序列化
      // users.value = users.value.map(item => JSON.parse(item));

    }
  }
  // console.log("users.value",users.value)
  wsCache.set(appStore.getChatUsersList, users.value);
}
//获取历史消息的最新一条

const formatDate = (dateStr) => {
    try {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) {
            throw new Error('Invalid date string');
        }

        const now = new Date();
        const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
        const diffDays = Math.round(Math.abs((now - date) / oneDay));

        if (diffDays === 0) {
            // 当天，显示时和分
            return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
        } else if (diffDays === 1) {
            // 昨天
            return '昨天';
        } else if (diffDays < 7) {
            // 最近一周内的日期
            return ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][date.getDay()];
        } else if (date.getFullYear() === now.getFullYear()) {
            // 今年
            return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' });
        } else {
            // 不是今年
            return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
        }
    } catch (error) {
        console.error('日期格式化错误:', error);
        return '无效日期';
    }
};
</script>

<style scoped>
#chat /deep/ .van-tab--active{
  font-size: 22px;
  /* font-weight: 600; */
}
.cust-van-tabs {
 /* padding-top: 20px; */
 /* background-color: #ffffff; */
  width:100%;
  height: 66px;
  background-color: #3286A0;
}

/**聊天卡片 */
.usersList {
  margin-top: 8px;
}
.my-van-image {
  vertical-align: middle;
}
.userInfo {
  vertical-align: middle;
  margin-left: 10px;
}
.userName {
  font-size: 15px;
}
.latest-new {
  color: rgb(167, 162, 162);
  font-size: 15px;
}

</style>